package net.sf.midollo.midlet.common;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class BaseMIDlet extends MIDlet implements CommandListener, Runnable {

  protected final Display display;
  protected CommandEventManager commandEventManager;
  protected Command exitCommand;
  protected Command okCommand;
  protected Thread thread;

  public BaseMIDlet() {
    this.display = Display.getDisplay(this);
  }

  public void run() {
  }

  protected void startApp() throws MIDletStateChangeException {
    if (this.thread == null) {
      this.exitCommand = new Command("Exit", Command.EXIT, 1);
      this.okCommand = new Command("OK", Command.OK, 1);
      this.thread = new Thread(this);
      this.thread.start();
    }
  }

  protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
    if (this.thread != null)
      this.thread.interrupt();
    if (!unconditional) {
      try {
        this.thread.join();
      } catch (InterruptedException ex) {
      }
    }
    notifyDestroyed();
  }

  protected void pauseApp() {
  }

  public void commandAction(Command c, Displayable d) {
    handleCommandAction(c, d);
  }

  protected boolean handleCommandAction(Command c, Displayable d) {
    if (c == this.exitCommand) {
      try {
        destroyApp(false);
      } catch (MIDletStateChangeException ex) {
      }
      return true;
    }
    if (this.commandEventManager != null) {
      this.commandEventManager.notifyCommand(c, d);
      return true;
    }
    return false;
  }
}
